#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
舆情监控系统启动脚本
一键启动监控和Web界面
"""

import subprocess
import threading
import time
import os
import sys
from sentiment_monitor import SentimentMonitor

def start_web_dashboard():
    """启动Web仪表板"""
    print("正在启动Web仪表板...")
    try:
        subprocess.run([sys.executable, "web_dashboard.py"], check=True)
    except Exception as e:
        print(f"启动Web仪表板失败: {e}")

def start_monitoring():
    """启动舆情监控"""
    print("正在启动舆情监控...")
    monitor = SentimentMonitor()
    
    try:
        # 执行首次监控
        print("执行首次舆情监控...")
        monitor.run_monitoring()
        
        # 显示初始结果
        articles = monitor.get_recent_articles(3)
        if articles:
            print("\n=== 发现的相关新闻 ===")
            for i, article in enumerate(articles, 1):
                print(f"{i}. {article[0][:50]}...")
                print(f"   来源: {article[2]}")
        
        print("\n开始定时监控（每30分钟执行一次）...")
        monitor.start_scheduled_monitoring()
        
    except KeyboardInterrupt:
        print("\n监控已停止")
    except Exception as e:
        print(f"监控过程中出错: {e}")
    finally:
        monitor.close()

def main():
    print("="*60)
    print("    舆情监控系统 - 青岛民营企业联合投资集团")
    print("="*60)
    print()
    
    # 检查依赖
    print("检查系统依赖...")
    try:
        import requests
        import bs4
        import flask
        import jieba
        print("✓ 依赖检查通过")
    except ImportError as e:
        print(f"✗ 缺少依赖: {e}")
        print("请运行: pip install -r requirements.txt")
        return
    
    print("\n选择启动模式:")
    print("1. 仅启动舆情监控")
    print("2. 仅启动Web仪表板")
    print("3. 同时启动监控和Web界面（推荐）")
    print("4. 执行一次性监控并查看结果")
    
    choice = input("\n请选择 (1-4): ").strip()
    
    if choice == "1":
        start_monitoring()
    elif choice == "2":
        start_web_dashboard()
    elif choice == "3":
        print("\n启动完整系统...")
        print("Web界面地址: http://localhost:5000")
        print("按 Ctrl+C 停止系统")
        
        # 在后台启动监控
        monitor_thread = threading.Thread(target=start_monitoring, daemon=True)
        monitor_thread.start()
        
        # 等待一下让监控先启动
        time.sleep(3)
        
        # 启动Web界面（主线程）
        start_web_dashboard()
        
    elif choice == "4":
        print("\n执行一次性监控...")
        monitor = SentimentMonitor()
        try:
            monitor.run_monitoring()
            
            articles = monitor.get_recent_articles(10)
            if articles:
                print("\n=== 监控结果 ===")
                for i, article in enumerate(articles, 1):
                    print(f"\n{i}. {article[0]}")
                    print(f"   来源: {article[2]} | 关键词: {article[3]}")
                    print(f"   链接: {article[1]}")
                    print(f"   时间: {article[4]}")
            else:
                print("\n未发现相关舆情信息")
                
        except Exception as e:
            print(f"监控失败: {e}")
        finally:
            monitor.close()
            
    else:
        print("无效选择")
        return
    
    print("\n系统已退出")

if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("\n\n系统已停止")
    except Exception as e:
        print(f"\n系统错误: {e}")